package com.me.libgdx_test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net.HttpMethods;
import com.badlogic.gdx.Net.HttpRequest;
import com.badlogic.gdx.Net.HttpResponse;
import com.badlogic.gdx.Net.HttpResponseListener;
import com.badlogic.gdx.net.HttpParametersUtils;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonWriter;
import com.me.libgdx_test.ClassUnlockablePrototypes.UnlockFactory;

public class ClassNetwork{
    
	private ClassLogDisplay logger;
	private ClassUnlockablePrototypes prototype_holder;
	private ActivityMain game;
	private boolean session_expired;
	private String base_url;
	private static String name = "BradZ";
	private static String email = "mauvemoonman@live.com";
	//dpgireesh89@gmail.com
	//private static String name = "Devika Gireesh";
	//private static String email = "dpgireesh89@gmail.com";
	//Stephy
	//private static String name = "Reaners";
	//private static String email = "snicollz@gmail.com";
	
    ClassNetwork(final ClassUnlockablePrototypes prototype_holder, ActivityMain game, boolean use_quest_server){
    	//Map<String, String> parameters = new HashMap<String, String>();
        //parameters.put("action", "save_user");
        //parameters.put("json", user.toJSON());

    	this.prototype_holder = prototype_holder;
        this.game = game;
        session_expired = true;
        
        if(use_quest_server){
        	base_url = "http://ec2-54-86-18-69.compute-1.amazonaws.com:3000/";
        }else{
        	base_url = "http://localhost:3000/";
        }
        
        //HttpRequest httpGet = new HttpRequest(HttpMethods.GET);
        //httpGet.setUrl("http://localhost:3000/users/get");
        
        logger = new ClassLogDisplay("ClassNetwork");
        logger.print("Network Initialized");
        //httpGet.setContent(HttpParametersUtils.convertHttpParameters(parameters));
    }
    
    public void get(){
    	String url_get_postfix = "get";
    	
    	logger.print("Sending Get Request");
    	HttpRequest httpGet = new HttpRequest(HttpMethods.GET);
        httpGet.setUrl(base_url + url_get_postfix);
        
        logger.print("url: " + httpGet.getUrl());
        
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("name", name);
        parameters.put("email", email);
        httpGet.setContent(HttpParametersUtils.convertHttpParameters(parameters));
        
        final String sent_url = httpGet.getUrl() + "?" + httpGet.getContent();
        logger.print("url: " + sent_url);
        
    	Gdx.net.sendHttpRequest(httpGet, new HttpResponseListener() {
			@Override
			public void handleHttpResponse (HttpResponse httpResponse) {
				try {
					//Only need to read the first line here
					logger.print("Received Get Data!");
					BufferedReader stream = new BufferedReader(new InputStreamReader(httpResponse.getResultAsStream()));
					
					String stringy = stream.readLine().replace("\\", "");
					logger.print(stringy);
					
					prototype_holder.set_factory(new Json().fromJson(UnlockFactory.class, stringy));
					//prototype_holder.get_factory().print_data();
					logger.print("End Get Data");
					game.init_activities();
					session_expired = false;
					//post();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			@Override
			public void failed (final Throwable t) {
				Gdx.app.postRunnable(new Runnable() {
					@Override
					public void run () {
						logger.print("Get Request Failed");
						logger.print("Expiring Session");
						session_expired = true;
						game.init_error(sent_url + "\n\n" + t.getMessage());
					}
				});
			}
		});
    }
    
    public void post(){
    	String url_post_postfix = "post";
    	
    	if(!session_expired){
	    	HttpRequest httpPost = new HttpRequest(HttpMethods.POST);
	        httpPost.setUrl(base_url + url_post_postfix);
	        
	        logger.print("Compiling Post Data...");
	        Map<String, String> parameters = new HashMap<String, String>();
	        parameters.put("name", name);
	        parameters.put("email", email);
	        Json json = new Json();
	        
	        //It is scary how necessary this one line of code is.
	        //If this isn't here there will not be any quotes around the json object being sent to the server.
	        //This will break the website if removed...
	        json.setOutputType(JsonWriter.OutputType.json);
	        
			String serialize_test = json.toJson(prototype_holder.get_factory(), UnlockFactory.class);
			logger.print(serialize_test);

	        parameters.put("meta", serialize_test);
	        httpPost.setContent(HttpParametersUtils.convertHttpParameters(parameters));
	        
	    	Gdx.net.sendHttpRequest(httpPost, new HttpResponseListener() {
				@Override
				public void handleHttpResponse (HttpResponse httpResponse) {
					try {
						//Only need to read the first line here
						logger.print("Received Post Data!");
						BufferedReader stream = new BufferedReader(new InputStreamReader(httpResponse.getResultAsStream()));
						logger.print(stream.readLine());
						//prototype_holder.set_factory(new Json().fromJson(UnlockFactory.class, stream.readLine()));
						logger.print("End Post Data");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				@Override
				public void failed (Throwable t) {
					Gdx.app.postRunnable(new Runnable() {
						@Override
						public void run () {
							logger.print("Post Request Failed");
							logger.print("Expiring Session");
							session_expired = true;
						}
					});
				}
			});
    	}else{
    		get();
    	}
    }
}